<template>
	<view class="collect-page">
		<!-- 加载中蒙版 -->
		<qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
		<!-- #ifdef MP-WEIXIN -->
		<!-- 顶部导航 -->
		<qmy-custom-navbar :top="42" :title="'我的收藏'"></qmy-custom-navbar>
		<!-- #endif -->
		<view :style="{paddingTop:menuObject.top + menuObject.height + 'px'}">

			<v-tabs ref="tabs" field="name" :fixed="true" :scroll="false" bgColor="#ffffff00" pillsColor="#ffffff00"
				fontSize="28rpx" pillsStyle="box" activeFontSize="30rpx" lineHeight="4rpx" :lineScale="0.2"
				activeColor="linear-gradient(to right, #14cc60, #14cc60)" paddingItem="0rpx 40rpx" @change="switchTab"
				color="linear-gradient(to right, #616161, #616161)" lineColor="#14cc60" :value="currentTab"
				:tabs="tabs"></v-tabs>
		</view>

		<!-- 列表内容区 -->
		<scroll-view :style="{paddingTop:menuObject.top + menuObject.height + 52 + 'px'}" scroll-y class="collect-list"
			@scrolltolower="loadMore" :refresher-enabled="true" :refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh">
			<!-- 空状态 -->
			<view v-if="list.length === 0" class="empty-box">
				<image src="https://gd-hbimg.huaban.com/935aa3edbe52e1b973e1f52ecd9b7003d2e5132e1c35-lqP6II_fw1200webp"
					mode="aspectFit"></image>
				<text>暂无收藏内容</text>
			</view>

			<!-- 商品类型 -->
			<template v-if="currentTab === 0">
				<view class="goods-item" v-for="item in list" :key="item._id"
					:class="{'invalid': !item.is_valid, 'slide-open': item.isOpen}"
					@touchstart="touchStart($event, item._id)" @touchmove="touchMove($event, item._id)"
					@touchend="touchEnd($event, item._id)">
					<view class="goods-content" @click="goDetail(item)">
						<view class="goods-main">
							<image class="goods-img" :src="item.target[0].goods_banner[0].url" mode="aspectFill">
							</image>
							<view class="goods-info">
								<text class="goods-name text-ellipsis">{{item.target[0].name}}</text>
								<view class="tags" v-if="item.target[0].tags && item.target[0].tags.length">
									<text class="tag-item" v-for="(tag,idx) in item.target[0].tags"
										:key="idx">{{tag}}</text>
								</view>
								<view class="goods-bottom">
									<text class="goods-price">¥{{item.target[0].default_price/100}}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="delete-btn" @click="deleteCollect(item,item.target[0])">
						<text class="iconfont ic-shanchu"></text>
					</view>
				</view>
			</template>

			<!-- 活动类型 -->
			<template v-if="currentTab === 1">
				<view class="activity-item" v-for="item in list" :key="item._id" @click="goDetail(item)"
					:class="{'invalid': !item.is_valid}">
					<image class="activity-img" :src="item.image" mode="aspectFill"></image>
					<view class="activity-info">
						<text class="activity-name text-ellipsis">{{item.name}}</text>
						<view class="activity-bottom">
							<view class="tags" v-if="item.tags && item.tags.length">
								<text class="tag-item" v-for="(tag,idx) in item.tags" :key="idx">{{tag}}</text>
							</view>
							<text class="delete-btn" @click.stop="deleteCollect(item)">删除</text>
						</view>
						<text v-if="!item.is_valid" class="invalid-tag">活动未通过审核或已失效</text>
					</view>
				</view>
			</template>

			<!-- 圈子类型 -->
			<template v-if="currentTab === 2">
				<view class="circle-item" v-for="item in list" :key="item._id" @click="goDetail(item)"
					:class="{'invalid': !item.is_valid}">
					<image class="circle-img" :src="item.image" mode="aspectFill"></image>
					<view class="circle-info">
						<text class="circle-name text-ellipsis">{{item.name}}</text>
						<view class="circle-bottom">
							<view class="tags" v-if="item.tags && item.tags.length">
								<text class="tag-item" v-for="(tag,idx) in item.tags" :key="idx">{{tag}}</text>
							</view>
							<text class="delete-btn" @click.stop="deleteCollect(item)">删除</text>
						</view>
						<text v-if="!item.is_valid" class="invalid-tag">帖子未通过审核或已失效</text>
					</view>
				</view>
			</template>

			<!-- 话题类型 -->
			<template v-if="currentTab === 3">
				<!-- 话题简介 -->
				<view class="topic-item" v-for="item in list" :key="item._id"
					:class="{'invalid': !item.is_valid, 'slide-open': item.isOpen}"
					@touchstart="touchStart($event, item._id)" @touchmove="touchMove($event, item._id)"
					@touchend="touchEnd($event, item._id)">
					<view class="topic-content" @click="goDetail(item)">
						<view class="topic-detail-header">
							<image class="topic-detail-cover" :src="item.target[0].cover_image" mode="aspectFill"
								lazy-load>
							</image>
							<view class="topic-detail-info">
								<view class="topic-detail-name">{{item.target[0].name}}</view>
								<view class="topic-detail-stats">
									<text>{{item.target[0].post_count || 0}} 内容</text>
									<text class="ml-10">{{item.target[0].follow_count || 0}} 关注</text>
								</view>
								<view class="topic-detail-desc text-element-2">{{item.target[0].description}}</view>
							</view>
						</view>
					</view>
					<view class="delete-btn" @click="deleteCollect(item,item.target[0])">
						<text class="iconfont ic-shanchu"></text>
					</view>
				</view>
			</template>
			<qmy-logo :loading="load" v-if="list.length"></qmy-logo>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif
				tabs: [{
					name: '商品',
					type: 1
				}, {
					name: '活动',
					type: 2
				}, {
					name: '圈子',
					type: 3
				}, {
					name: '话题',
					type: 4
				}],
				currentTab: 0,
				list: [],
				page: 1,
				pageSize: 10,
				isRefreshing: false,
				startX: 0,
				currentId: '',
				deleteWidth: 100,
				touchStartTime: 0,
				dataLoaded: false,
				hasMore: true,
				scrollHeight: 200,
				load: false, // 是否加载中
			}
		},
		onLoad() {
			this.$nextTick(() => {
				this.scrollHeight = this.menuObject.top + this.menuObject.height + 42
			})
			this.getCollectList()
		},
		methods: {

			// 切换标签
			switchTab(index) {
				if (this.currentTab === index) return
				this.currentTab = index
				this.page = 1
				this.hasMore = true
				this.list = []
				this.getCollectList()
			},

			// 获取收藏列表
			async getCollectList(type = 'refresh') {
				this.load = true;
				this.$Route('get-private-data', true).getCollectList({
					type: this.tabs[this.currentTab].type,
					page: this.page,
					pageSize: this.pageSize
				}).then(res => {
					if (type === 'refresh') {
						this.list = res.data
					} else {
						this.list = [...this.list, ...res.data]
					}
					this.hasMore = res.data.length === this.pageSize
				}).catch(err => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				}).finally(() => {
					this.load = false;
					this.dataLoaded = true
					this.isRefreshing = false
				})
			},

			// 加载更多
			loadMore() {
				if (!this.hasMore) return this.$Toast('没有更多数据了')
				this.page++
				this.getCollectList('more')
			},

			// 下拉刷新
			onRefresh() {
				this.isRefreshing = true
				this.page = 1
				this.hasMore = true
				this.getCollectList()
			},

			// 删除收藏
			async deleteCollect(item,target) {
				let type = 'goods'
				switch (this.tabs[this.currentTab].type) {
					case 1:
						type = 'goods'
						break
					case 2:
						type = 'activity'
						break
					case 3:
						type = 'circle'
						break
					case 4:
						type = 'topic'
						break
				}
				this.$Route('add-private-data').addToCollect(target, type).then(res => {
					this.list = this.list.filter(i => i._id !== item._id) // 删除列表中的收藏项
				}).catch(err => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				})
			},

			// 跳转详情
			goDetail(item) {
				const type = this.tabs[this.currentTab].type
				let url = ''

				switch (type) {
					case 1:
						url = `/pages/detail/goodsDetail?id=${item.target_id}`
						break
					case 2:
						url = `/pages/detail/activityDetail?id=${item.target_id}`
						break
					case 3:
						url = `/pages/detail/circleDetail?id=${item.target_id}`
						break
					case 4:
						url = `/pages/detail/topicDetail?id=${item.target_id}`
						break
				}

				this.$NavigateTo(url)
			},

			// 触摸开始
			touchStart(e, id) {
				// 记录触摸开始时间
				this.touchStartTime = Date.now();

				// 关闭其他已打开的滑动项
				this.list.forEach(item => {
					if (item._id !== id) {
						item.isOpen = false;
					}
				});

				this.startX = e.touches[0].clientX;
				this.currentId = id;
			},

			// 触摸移动
			touchMove(e, id) {
				if (id !== this.currentId) return;

				const moveX = e.touches[0].clientX;
				const moveDistance = moveX - this.startX;

				// 找到当前操作的项
				const currentItem = this.list.find(item => item._id === id);
				if (!currentItem) return;

				// 只允许向左滑动
				if (moveDistance > 0) {
					currentItem.isOpen = false;
					return;
				}

				// 滑动距离超过阈值时打开删除按钮
				if (Math.abs(moveDistance) > this.deleteWidth / 2) {
					currentItem.isOpen = true;
				} else {
					currentItem.isOpen = false;
				}
			},

			// 触摸结束
			touchEnd(e, id) {
				if (id !== this.currentId) return;

				// 找到当前操作的项
				const currentItem = this.list.find(item => item._id === id);
				if (!currentItem) return;

				// 如果是点击（触摸时间小于200ms且移动距离小于5px）
				const touchEndTime = Date.now();
				const touchDuration = touchEndTime - this.touchStartTime;
				const moveDistance = Math.abs(e.changedTouches[0].clientX - this.startX);

				if (touchDuration < 200 && moveDistance < 5) {
					currentItem.isOpen = false;
				}

				this.currentId = '';
			}
		}
	}
</script>

<style lang="scss">
	.collect-page {
		min-height: 100vh;
		background-color: #f7f8fa;
	}

	.tabs {
		display: flex;
		background-color: #fff;
		padding: 0 30rpx;
		position: sticky;
		top: var(--window-top);
		z-index: 100;

		.tab-item {
			flex: 1;
			text-align: center;
			font-size: 28rpx;
			color: #666;
			position: relative;
			padding: 20rpx 0;

			&.active {
				color: #14cc60;
				font-weight: 600;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background-color: #14cc60;
					border-radius: 2rpx;
				}
			}
		}
	}

	.collect-list {
		position: fixed;
		top: 0;
		bottom: 0;
		padding: 20rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.empty-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 200rpx;
		opacity: 0.5;

		image {
			width: 150rpx;
			height: 150rpx;
			margin-bottom: 20rpx;
		}

		text {
			font-size: 28rpx;
			color: #999;
		}
	}

	.text-ellipsis {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	// 失效状态样式
	.invalid {
		opacity: 0.6;
	}

	.invalid-tag {
		position: absolute;
		bottom: 16rpx;
		right: 16rpx;
		background: rgba(0, 0, 0, 0.6);
		color: #fff;
		font-size: 20rpx;
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
	}

	// 商品样式
	.goods-item {
		position: relative;
		margin-bottom: 20rpx;
		overflow: hidden;
		background-color: #fff;
		border-radius: 20rpx;

		.goods-content {
			position: relative;
			z-index: 2;
			background-color: #fff;
			transform: translateX(0);
			transition: transform 0.3s ease;
		}

		.goods-main {
			display: flex;
			padding: 20rpx;
		}

		.goods-img {
			width: 160rpx;
			height: 160rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
			background-color: #f7f8fa;
		}

		.goods-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			min-width: 0;

			.goods-name {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 12rpx;
			}

			.tags {
				display: flex;
				flex-wrap: wrap;
				margin-bottom: 12rpx;

				.tag-item {
					padding: 2rpx 12rpx;
					color: #14cc60;
					background-color: rgba(20, 204, 96, 0.1);
					font-size: 20rpx;
					border-radius: 4rpx;
					margin-right: 12rpx;
					margin-bottom: 8rpx;
				}
			}

			.goods-bottom {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.goods-price {
					font-size: 32rpx;
					color: #ff4f4f;
					font-weight: 600;
				}
			}
		}

		.delete-btn {
			position: absolute;
			top: 0;
			right: 0;
			width: 100rpx;
			height: 100%;
			background-color: #ff4f4f;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1;

			.iconfont {
				color: #fff;
				font-size: 40rpx;
			}
		}

		&.slide-open {
			.goods-content {
				transform: translateX(-100rpx);
			}
		}
	}

	// 活动和圈子公共样式
	.activity-item,
	.circle-item {
		background-color: #fff;
		border-radius: 20rpx;
		margin-bottom: 24rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
		}

		.activity-img,
		.circle-img {
			width: 100%;
			height: 320rpx;
			transition: all 0.3s ease;

			&:hover {
				transform: scale(1.02);
			}
		}

		.activity-info,
		.circle-info {
			padding: 24rpx;

			.activity-name,
			.circle-name {
				font-size: 32rpx;
				color: #2c3e50;
				font-weight: 600;
				margin-bottom: 16rpx;
			}

			.activity-bottom,
			.circle-bottom {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 16rpx;
			}
		}
	}

	.tags {
		display: flex;
		flex-wrap: wrap;

		.tag-item {
			padding: 6rpx 20rpx;
			color: #14cc60;
			background-color: rgba(20, 204, 96, 0.1);
			font-size: 24rpx;
			border-radius: 24rpx;
			margin-right: 16rpx;
			margin-bottom: 12rpx;
		}
	}

	.delete-btn {
		font-size: 26rpx;
		color: #8a919f;
		padding: 10rpx 30rpx;
		border: 2rpx solid #e5e9ef;
		transition: all 0.3s ease;

		&:active {
			background: #f8f9fa;
			border-color: #d0d7de;
		}
	}

	// 话题样式
	.topic-item {
		position: relative;
		background-color: #fff;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;

		.topic-content {
			position: relative;
			z-index: 2;
			background-color: #fff;
			transform: translateX(0);
			transition: transform 0.3s ease;
			padding: 24rpx;
		}

		.delete-btn {
			position: absolute;
			top: 0;
			right: 0;
			width: 100rpx;
			height: 100%;
			background-color: #ff4f4f;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1;

			.iconfont {
				color: #fff;
				font-size: 40rpx;
			}
		}

		&.slide-open {
			.topic-content {
				transform: translateX(-100rpx);
			}
		}
	}

	.topic-item:active {
		transform: scale(0.99);
	}

	.topic-detail-header {
		display: flex;
		align-items: center;
	}

	.topic-detail-cover {
		width: 140rpx;
		height: 140rpx;
		border-radius: 12rpx;
		margin-right: 24rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		flex-shrink: 0;
	}

	.topic-detail-info {
		flex: 1;
		display: flex;
		height: 140rpx;
		flex-direction: column;
		justify-content: space-between;
		min-width: 0;
	}

	.topic-detail-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.topic-detail-stats {
		font-size: 24rpx;
		color: #888;
		display: flex;
		align-items: center;
	}

	.ml-10 {
		margin-left: 10rpx;
	}

	.topic-detail-stats text:first-child::after {
		content: '•';
		margin: 0 6rpx;
		color: #ccc;
	}

	.topic-detail-desc {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}

	.text-element-2 {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}
</style>